<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require("base_c.php");

/**
* Created by PhpStorm.
* User: LEEYOOL
* Date: 1/21/15
* Time: 8:41 AM
*/

class profile_c extends base_c {

    public function index() 
    {
        $total = $this->base_m->getTotal('users', 0, 0, 0);
        $page_current = $this->uri->segment(3);
        if (!$page_current) {
            $page_current = 0;
        }
        $config['base_url'] = base_url()."thanh-vien/page";
        $config['total_rows'] = $total;
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['full_tag_open'] = '<div class="pagination">';
        $config['full_tag_close'] = '</div>';
        $this->pagination->initialize($config);

        $this->data['articleItems'] = $this->base_m->getPaging('users', 0, 0, 0, $page_current, $config['per_page']);        
        $this->data['page'] = 'profiles';

        $this->data['title'] = 'Thành viên';
        $this->data['keywords'] = '';
        $this->data['description'] = '';
        $this->load->view('layout', $this->data);
    }

    public function profile_detail() 
    {
        $id_seg = end(explode('-', $this->uri->segment(2)));
        if(is_numeric($id_seg))
        {
            $user_item = $this->profile_m->getUser($id_seg);
            $this->data['user_item'] = $user_item;
            $this->data['calendar_item'] = $this->calendar_m->getCalendars($user_item->id);

            $this->data['page'] = 'profiles-detail';
            $this->data['title'] = $user_item->username;
            $this->data['keywords'] = '';
            $this->data['description'] = mb_substr(strip_tags($user_item->content),  0, 256, "utf-8");
            $this->load->view('layout', $this->data);
        }
    }

    public function profile_edit () {
        if($this->session->userdata('user_id')!="")
        {      
            $id = $this->session->userdata('user_id');
            $user_item = $this->profile_m->getUser($id);
            $this->data['user_item'] = $user_item;
            $this->data['calendar_item'] = $this->calendar_m->getCalendars($user_item->id);
            $path = str_replace("application", "", realpath(APPPATH))."/assets/images/avatar/";

            $this->data['cityItems'] = $this->city_m->getCity();

            if($this->input->post('updateMember') == TRUE)
            {
                if($_FILES['image']['tmp_name'])
                {
                    $image_tmp1 = ($_FILES['image']['tmp_name']);
                    $filename1 = stripslashes($_FILES['image']['name']);
                    $extension1 = $this->base_m->getExtension($filename1);
                    $extension1 = strtolower($extension1);
                    $filesize1 = filesize($_FILES['image']['tmp_name']);
                    $imageName1 = ($_FILES['image']['name']);
                    $imageName1 = "avatar-".$id."-".$imageName1;
                    if ($extension1 != "jpg" && $extension1 != "png" && $extension1 != "jpeg" && $extension1 != "bmp") {
                        echo "
                        <script>
                            alert('Format image incorrect! Please try again!');
                            window.location = '".base_url('thanh-vien/tai-khoan')."';
                        </script>
                        ";
                    } elseif ($filesize1 > 2097152) {
                        echo "
                        <script>
                            alert('Image size exceed 2MB! Please down image size and try again!');
                            window.location = '".base_url('thanh-vien/tai-khoan')."';
                        </script>
                        ";
                    } else {
                        move_uploaded_file($image_tmp1, $path . "/" . $imageName1);
                        $data = array (
                            'skill' => $this->input->post('inputSkill'),
                            'tel_viber' => $this->input->post('inputTel'),
                            'facebook' => $this->input->post('inputFacebook'),
                            'content' => $this->input->post('inputNoidung'),
                            'city_id' => $this->input->post('cmbCity'),
                            'image' => $imageName1
                            );
                        if($this->profile_m->updateUser($data, $id))
                        {
                            echo "<meta charset='utf-8'>";
                            echo "
                            <script language='javascript' >
                                alert('Cập nhật thành công');
                                window.location = '".base_url('thanh-vien')."';
                            </script>
                            ";
                        } 
                        else
                        {
                            echo "<meta charset='utf-8'>";
                            echo "
                            <script language='javascript' >
                                alert('Cập nhật thất bại');
                            </script>
                            ";
                        }
                    }
                } 
                else
                {
                    $data = array (
                        'skill' => $this->input->post('inputSkill'),
                        'tel_viber' => $this->input->post('inputTel'),
                        'facebook' => $this->input->post('inputFacebook'),
                        'content' => $this->input->post('inputNoidung'),
                        'city_id' => $this->input->post('cmbCity'),
                        );
                    if($this->profile_m->updateUser($data, $id))
                    {
                        echo "<meta charset='utf-8'>";
                        echo "
                        <script language='javascript' >
                            alert('Cập nhật thành công');
                            window.location = '".base_url('thanh-vien')."';
                        </script>
                        ";
                    } 
                    else
                    {
                        echo "<meta charset='utf-8'>";
                        echo "
                        <script language='javascript' >
                            alert('Cập nhật thất bại');
                        </script>
                        ";
                    }
                }
                
            }
            else
            {
                $this->data['page'] = 'profiles-edit';
            }  

            $this->data['title'] = "Cập nhật thông tin thành viên: " .$user_item->username;
            $this->data['keywords'] = '';
            $this->data['description'] = mb_substr(strip_tags($user_item->content),  0, 256, "utf-8");
            $this->load->view('layout', $this->data);
        }
        else 
        {
            echo "<meta charset='utf-8'>";
            echo "
            <script language='javascript' >
                alert('Bạn chưa đăng nhập! Vui lòng đăng nhập để cập nhật thông tin.');
                setTimeout(function(){
                    window.location = '".base_url()."';
                }, 10);
        </script>
        ";
        }   
    }

    public function login()
    {
        $email = $this->input->post('email');
        $pass = md5(sha1($this->input->post('password')));
        $userItem = $this->profile_m->login($email, $pass);
        if(!is_null($userItem))
        {
            $this->session->set_userdata('user_id', $userItem->id);
        }
        $this->load->view('partials/login-form', $this->data);
    }

    public function logout() 
    {
        $this->session->unset_userdata('user_id');
        $this->session->sess_destroy();
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function register() 
    {
        if($this->input->post('register') == TRUE)
        {
            echo "<meta charset='utf-8'>";
            $name = $this->input->post('fullname');
            $email = $this->input->post('email');
            $pass = $this->input->post('password');
            $re_pass = $this->input->post('confirmpassword');
            if (strcmp($pass, $re_pass) !== 0) 
            {
                echo "
                <script language='javascript' >
                    alert('Mật khẩu không trùng nhau. Xin vui lòng thữ lại.');
                    setTimeout(function(){history.back();}, 10);
                </script>
                ";
                return;
            } 
            else
            {
                if ($this->profile_m->checkEmail($email) > 0) {
                    echo "
                    <script language='javascript' >
                        alert('Email này đã tồn tại! Vui lòng sữ dụng Email khác!');
                        setTimeout(function(){history.back();}, 10);
                    </script>
                    ";
                    return;
                } 
                else 
                {
                    $data = array(
                        username => $name,
                        slug => mb_strtolower(url_title($this->slug->removesign($name))),
                        email => $email,
                        password => md5(sha1($re_pass))
                        );
                    $this->profile_m->createUser($data);
                    redirect(base_url());
                }
            }
        }
        else
        {      
            $this->data['title'] = 'Đăng ký thành viên';
            $this->data['keywords'] = '';
            $this->data['description'] = '';
            $this->data['page'] = 'register'; 
        }  
        $this->load->view('layout', $this->data);
    }

    public function add_tour()
    {
        if($this->session->userdata('user_id')!="")
        {
            $id = $this->session->userdata('user_id');
            $user_item = $this->profile_m->getUser($id);
            $this->data['user_item'] = $user_item;
            $this->data['calendar_item'] = $this->calendar_m->getCalendars($user_item->id);

            $name = $this->input->post('name');
            echo $date_start = date("Y-m-d", strtotime($this->input->post('date_start')));
            echo $date_end = date("Y-m-d", strtotime($this->input->post('date_end')));


            if($name == "" || $date_start == "" || $date_end == "" || $date_start == "1970-01-01" || $date_end == "1970-01-01")
            {                
                echo "<meta charset='utf-8'>";
                echo "
                <script language='javascript' >
                    alert('Trường bắt buộc không được để trống ^^');
                    setTimeout(10);
                </script>
                ";
            }
            else
            {
                if($date_start > $date_end)
                {
                    echo "<meta charset='utf-8'>";
                    echo "
                    <script language='javascript' >
                        alert('Ngày bắt đầu tour và ngày kết thúc tour không hợp lệ!');
                        setTimeout(10);
                    </script>
                    ";
                }
                else
                {
                    $data = array(
                        'user_id' => $id,
                        'name' => $name,
                        'date_start' => $date_start,
                        'date_end' => $date_end
                        );
                    if($this->profile_m->addTour($data))
                    {
                        echo "<meta charset='utf-8'>";
                        echo "
                        <script language='javascript' >
                            alert('Thêm Tour thành công!');
                        </script>
                        ";
                    }
                    else
                    {
                        echo "<meta charset='utf-8'>";
                        echo "
                        <script language='javascript' >
                            alert('Thêm Tour thất bại! Vui lòng thữ lại');
                            setTimeout(function(){history.back();}, 10);
                        </script>
                        ";
                    } 
                    $this->load->view('partials/calendar-member', $this->data);    
                }
            }

        }
        else
        {
            {
                echo "<meta charset='utf-8'>";
                echo "
                <script language='javascript' >
                    alert('Bạn chưa đăng nhập! Vui lòng đăng nhập để cập nhật thông tin.');
                    setTimeout(function(){
                        window.location = '".base_url()."';
                    }, 10);
                </script>
                ";
            }
        }
    }

    public function member_search()
    {
        $keyword = $_POST['key'];
        $area_id = $_POST['area'];
        $city_id = $_POST['city'];

        $this->data['articleItems'] = $this->base_m->getMemberSearch($keyword, $area_id, $city_id, 0);
        $this->load->view('partials/member-list', $this->data);
    }
}